<template>
  <div class="app" :class="[{
    has_header: state.hasHeader
  }]" onselectstart="return false;">
    <nut-navbar v-if="state.hasHeader" class="navbar app_header" :style="headerStyle ? { ...headerStyle } : null" z-index="5" :clickable="false">
      <template #content>
        <span style="line-height: 22px;">{{ titleStr }}</span>
      </template>
      <template #left>
        <iconpark-icon @click="onClickLeft" class="close" name="back" size="1.5rem"></iconpark-icon>
      </template>
      <template #right v-if="isLocalLoggedIn">
        <div class="amount_box" v-if="['gameDetail'].includes(route.name)">
          <iconpark-icon class="close" icon-id="dong1" size="1.2rem"></iconpark-icon>
          <span>
            <nut-price :price="convert2DisplayMoney(roleInfo.money)" size="small" style="color: #ffd56d"
              :decimal-digits="0" thousands :need-symbol="false" /></span>

          <Imgt class="plus" src="/imgs/home/plus.png" :key="'plus'" @click="router.push('deposit')"></Imgt>
        </div>
      </template>
    </nut-navbar>

    <div v-if="pageLoading || langLoading"
      style="width: 100%;height: 100%;position: fixed;top: 0;left: 0;display: flex;align-items: center;justify-content: center;">
      <LoadingCircle />
    </div>
    <RouterTransition v-show="!pageLoading" v-if="!langLoading" class="router-page" :hasHeader="state.hasHeader" />

    <nut-tabbar z-index="2" v-if="state.hasTabbar && !langLoading" route v-model="state.active" bottom
      :before-switch="beforeSwitch">
      <nut-tabbar-item class="item" :name="item.name" @click.stop="tabbarClick(item)"
        v-for="(item, i) in state.tablebarArr" :key="i">{{ t(item.text) }}
        <template #icon="props">
          <span class="tt" v-if="item.isWallet" id="pop_target">
            <SvgaItem :keyStr="i" name="jinbi" :active="state.popoverShow" :loopNumber="1" class="tabbar_icon_1" />
          </span>
          <nut-badge :dot="!!(item.name == 'me' && page.unread)" v-else-if="item.isMe">
            <iconpark-icon :icon-id="props.active ? item.active : item.unactive" size="1.4rem"></iconpark-icon>
          </nut-badge>
          <iconpark-icon :icon-id="props.active ? item.active : item.unactive" size="1.4rem" v-else></iconpark-icon>
        </template>
      </nut-tabbar-item>
    </nut-tabbar>

    <div class="popover_bg" v-if="state.hasTabbar" :class="[{ 'pop_height': state.popoverShow }]">
      <div class="popover_bg_close" @click="state.popoverShow = false"></div>
      <div class="popover_bg_main" :class="[{ 'pop_height_main': state.popoverShow }]">
        <div v-for="(v, j) in state.walletList" :key="j" @click="onClickToPage(v)">
          <ImgT :src="v.img" :key="v.img" :alt="v.text" />
          <span>{{ t(v.text) }}</span>
        </div>
      </div>
    </div>

    <nut-overlay v-model:visible="isPopShow" :close-on-click-overlay="false" :lock-scroll="true" :overlay-style="{
      backgroundColor: 'rgba(0, 0, 0, .5)',
    }">
      <div class="login_pop">
        <Login v-if="isLogin"></Login>
        <!-- 注册弹窗 -->
        <Register v-if="isReg" />
        <!-- 注册退出弹窗 -->
        <RegisterQuit v-if="isRegQuit" />
        <ForgotPassword v-if="isForget"></ForgotPassword>
      </div>
    </nut-overlay>

    <!-- 公告弹窗 -->
    <Notice ref="noticeRef"></Notice>
    <!-- 异地登录 -->
    <Modal :pop-class="'diffoffline'" :title="t('home_page_diffOfflineTitle')" @close="diffOfflineObj.show = false" :visible="diffOfflineObj.show"
      :showClose="true">
      <div class="diff_offline_dialog">
        <div>{{ diffOfflineObj.content }}</div>
        <div class="btn" @click="diffOfflineObj.show = false">{{ t("confirm") }}</div>
      </div>
    </Modal>
  </div>
  <!-- <nut-overlay v-model:visible="state.show">
    <div class="overlay_body">
      <SvgaItem keyStr="xz" name="xz" :active="true" style="width: 20vw; height: 20vw" class="overla_content" />
    </div>
  </nut-overlay> -->
  <!-- 右侧侧滑页面 -->
  <template v-if="homeGameData.length">
    <nut-popup :visible="showRight" :overlay="false" :lock-scroll="true" position="right"
      :style="{ width: '100%', height: '100%', backgroundColor: 'rgba(0,0,0,0)' }">
      <div style="display: flex;flex-direction: column;overflow: hidden;height: 100%;">
        <rightCategory />
      </div>
    </nut-popup>
  </template>


  <!-- <OverLoading v-model:visible="gameIsLoading"></OverLoading> -->
</template>
<script setup lang="ts">
import { watch, reactive, ref, onBeforeMount, defineAsyncComponent, computed, onMounted, onBeforeUnmount, provide } from "vue";
import { useRoute, useRouter } from "vue-router";
// import HomeHeader from "./views/home/components/homeHeader.vue";
import pinia from "@/store/index";
import { storeToRefs } from "pinia";
import { User } from "@/store/user";
import { Page } from "@/store/page";
import { NetPacket } from "./netBase/NetPacket";
import PKwebsocket from "@/lolo/Ws";
import eventBus from "@/lolo/eventBus";
import Imgt from "./components/Imgt.vue";
import {
  bankPayMethods,
  bankPayType,
  convertObjectToDateString,
} from "./utils/publicMethods";
import { useI18n } from "vue-i18n";
import { showDialog, showNotify, showToast } from "@nutui/nutui";
// import { useRouteStack } from '@/hooks/useRouteStack';
import { convert2DisplayMoney, getIPAddress, unserialize } from "@/utils/useStoreMethods";
import { getLocale } from "./main";
import { Local } from "./utils/storage";
import { SystemStore } from "@/store/system"
import SvgaItem from "@/components/SvgaItem.vue"
import Notice from "@/components/Notice.vue"
import Modal from "@/components/Modal.vue"
import rightCategory from "@/views/category/rightCategory.vue"
import { usePreventSwipeByClass } from '@/hooks/usePreventSwipeByClass';
import RouterTransition from '@/components/RouterTransition.vue';
import LoadingCircle from '@/components/LoadingCircle.vue';

// const category = defineAsyncComponent(() => import("@/views/category/index.vue"));
const Login = defineAsyncComponent(() => import("@/components/Login.vue"));
const Register = defineAsyncComponent(() => import("@/components/Register.vue"));
const RegisterQuit = defineAsyncComponent(() => import("@/components/RegisterQuit.vue"));
const ForgotPassword = defineAsyncComponent(() => import("@/components/ForgotPassword.vue"));
// const OverLoading = defineAsyncComponent(() => import("@/components/Loading.vue"));
usePreventSwipeByClass({
  excludedPaths: [/\/recentWin\/detail/]
});
const { t } = useI18n();
const page = Page(pinia);
const user = User(pinia);
const system = SystemStore(pinia);

const { settings, showRight, homeGameData, isBackFromGame, pageLoading, langLoading } = storeToRefs(page);
const { allCollected, isLocalLoggedIn, shopInfoData, bankCardInfoList, isLogin, isReg, isRegQuit, isForget, roleInfo, myEmail } = storeToRefs(user);
const isPopShow = computed(
  () => isLogin.value || isReg.value || isRegQuit.value || isForget.value
);
const route: any = useRoute();
const router = useRouter();
const headerStyle = ref({
  background: 'transparent'
})

provide('headerStyle', headerStyle)

// const { isBack } = useRouteStack(router);
const state: any = reactive({
  isMainDeposit: false, // 是否全部充值方式都维护
  isMainWidthdraw: false, // 是否全部提现方式都维护
  show: false,
  popoverShow: false,
  active: "home",
  hasHeader: false,
  hasTabbar: true,
  title: "",
  leftIcon: "",
  rightIcon: "",
  routeName: "home",
  tablebarArr: [
    {
      text: "route_page_home",
      name: "home",
      active: "home",
      unactive: "home1",
      url: "/",
      show: false,
      id: 1,
    },
    {
      text: "route_page_category",
      name: "categoryPage",
      active: "category",
      unactive: "category1",
      url: "/categoryPage",
      show: false,
      id: 2,
    },
    {
      text: "route_page_transaction",
      name: "",
      active: "",
      unactive: "",
      url: "",
      isWallet: true,
      show: false,
      id: 3,
    },
    {
      text: "route_page_activity",
      name: "activity",
      active: "activity",
      unactive: "activity1",
      url: "/activity",
      show: false,
      id: 4,
    },
    {
      text: "route_page_me",
      name: "me",
      active: "me",
      unactive: "me1",
      url: "/me",
      isMe: true,
      show: false,
      id: 5,
    },
  ],
  walletList: [
    {
      text: "route_page_wallet",
      img: "/imgs/tabbar/qb.webp",
      url: "/myWallet",
    },
    {
      text: "route_page_deposit",
      img: "/imgs/tabbar/cz.webp",
      url: "/deposit",
      key: "deposit",
    },
    {
      text: "route_page_withdrawals",
      img: "/imgs/tabbar/tx.webp",
      url: "/withdrawals",
      key: "withdrawals",
    },
  ],
});

const onClickLeft = () => {
  if (String(route.name) == "gameDetail") {
    Local.remove("agentId");
    router.replace("/");
  } else if (route.path.includes('shortcut')) {
    router.replace(Local.get('chatRoomUrl'))
  }else if(route.name=='securitySettings'){
    router.replace("/me");
  } else {
    router.back();
  }
};


const onClickToPage = (item: any) => {
  state.popoverShow = false;
  if (!isLocalLoggedIn.value) {
    user.setLogin(true);
    return;
  }
  // 充值维护
  if (item?.key === "deposit" && state.isMainDeposit) {
    return;
  }
  // 提现维护
  if (item?.key === "withdrawals" && state.isMainWidthdraw) {
    return;
  }
  router.push(`${item.url}`);
};

const beforeSwitch = (item: any) => {
  if (!item.name) {
    state.popoverShow = !state.popoverShow;
    state.active = "";
    return false;
  } else {
    state.popoverShow = false;
    state.active = item.name;
    router.push(item.to);
    return false;
  }
};
const leftIcon = (name: string) => {
  switch (name) {
    case "home":
      return "bars";

    default:
      return "tongyicontyfanh";
  }
};
const rightIcon = (name: string) => {
  switch (name) {
    case "name":
      return "";
    default:
      return "service";
  }
};
const title = (name: string) => {
  if (name == "gameDetail" && homeGameData.value.length) {
    const data = homeGameData.value.find(
      (e: any) => e.id == Number(route.query.venue_id)
    );
    if (data && data.name) {
      return unserialize(data.name, false); // name as strin
    }
    return t(String(route.meta.title));
  } else {
    return t(String(route.meta.title));
  }
};
const titleStr = computed(() => {
  return title(String(route.name))
})


const init = (name: string) => {
  //头部导航不显示
  state.hasHeader = ![
    "home",
    "insidePages",
    "activity",
    "me",
    // "vip",
    "trans",
    "myWallet",
    "undefined",
    "openGame",
    "chatList",
    "chatRoom",
    "friendsList",
    "clubCreate",
    "record",
    "category",
    "categoryPage",
    "hotGameDetail",
    "searchGames",
    "member",
    "member",
    "club",
    "myClub",
    "approvalMenber",
    "allMember",
    "clubDetail",
    "handList",
    "eventDetails",
    "clubHandList",
    "myHandList",
    "game",
    "withdrawals",
    "withdrawalNext",
  ].includes(String(name));
  // console.log('========', name)
  // 底部tabBar不显示
  state.hasTabbar = [
    "home",
    "me",
    "activity",
    "categoryPage",
    // "undefined",
    // "chatList",
    // "chatRoom",
    // "friendsList",
    // "shortcut",
    // "openGame",
    // "freeLoot",
    // "hotGameDetail",
    // "searchGames",
    // "activityDetail",
    // "redEnvelope",
    // "deposit",
    // "depositNext",
  ].includes(String(name));

  // state.hasTabbar = ['home', 'activity', 'me', 'vip', 'trans'].includes(String(name))
  state.leftIcon = leftIcon(name);
  state.rightIcon = rightIcon(name);
  state.title = title(name);
  state.active = name;
};
// const pageLoading = ref(false)


// 公告消息
const noticeRef = ref();
const onHander_system_notice = async (message: any) => {
  console.log('isBackFromGame notice', isBackFromGame.value)
  if (isBackFromGame.value) {
    resetBackFromGameStatus()
    return;
  }
  if (message.notice_list?.length) {
    const dialogList: any = message.notice_list.filter((item: any) => item.position == 1);
    const paomaList: any = message.notice_list.filter((item: any) => item.position == 0);

    // 弹窗公告
    let localIds = []; // 本地记录的不再显示
    try {
      localIds = JSON.parse(localStorage.getItem("readed_notice_ids") || "[]");
    } catch {
      localIds = [];
    }
    const list: any = dialogList
      .filter((item: any) => !localIds.includes(item.title))
      .sort((a: any, b: any) => {
        return b.priority - a.priority;
      });
    // console.error('弹窗公告', list)
    if (list.length) {
      await getLocale(settings.value);
      await user.setNoticeList(list);
      user.setNotice(true);
      noticeRef.value && noticeRef.value.open();
    }

    // 轮播公告
    paomaList.forEach((item: any) => {
      page.setTextAnnouncementMore(t(item.title) + " - " + t(item.content));
    });
  }
};


// 消息通知
const onHandler_system_msg = async (m: any) => {
  // console.error('----系统消息', m)
  if (m.code == 903) {
    if (m.Params[0] == 1) {
      // 弹窗公告
      try {
        const list: any = [
          {
            content: `${m.Params[3]}`,
            title: `${m.Params[2]}`,
            position: 1,
            priority: m.priority,
            type: m.Params[1],
          },
        ];
        await getLocale(settings.value);
        await user.setNoticeList(list);
        user.setNotice(true);
        noticeRef.value && noticeRef.value.open();
      } catch {
        console.error("error msg", m);
      }
    }
  } else {
    if (m.Params && m.Params.length == 6) {
      // 跑马灯
      // ***[0]*** 在 [3] 获得 [4] 金币奖励！
      const str = t("home_notice_mixtext", {
        user: `${m.Params[0]?.substr(0, 4)}***`,
        game: m.Params[3] ? t(m.Params[3]) : "",
        money: m.Params[4] ? Number(m.Params[4]).toLocaleString() : 0,
      });
      page.setTextAnnouncementMore(str);
    }
  }
};

// 异地登录
const diffOfflineObj: any = ref({
  show: false,
  content: "",
});
const getDeviceType = (device_id: any) => {
  if (device_id == 1) return "WEB";
  if (device_id == 2) return "Android";
  if (device_id == 3) return "IOS";
  return t("else");
};

let resetBackFromGameStatusTimer: any = null
const resetBackFromGameStatus = () => {
  // 延时3s是因为有多个需要根据这个状态变化有时差,还有公告通知会有2个
  resetBackFromGameStatusTimer && clearTimeout(resetBackFromGameStatusTimer);
  resetBackFromGameStatusTimer = setTimeout(() => {
    Page(pinia).setBackFromGame(false);
  }, 3500)
}

const diffOfflineFunc = async (res: any) => {
  console.log('isBackFromGame', isBackFromGame.value)
  if (isBackFromGame.value) {
    resetBackFromGameStatus()
    return;
  }
  // 您的账号上次在2024-05-28 19:20:02于xx的xx设备登录，如非本人操作，则密码可能泄露，建议您修改密码
  console.error("异地登录", res);
  // let ipText = res.ip;
  res.ip && (await getIPAddress([res])); //  await getIP(res.ip);
  diffOfflineObj.value.show = true;
  diffOfflineObj.value.content = t("home_page_diffOfflineContent", {
    time: convertObjectToDateString(res.login_time),
    device: res.device_id ? getDeviceType(res.device_id) : "",
    ip: res.location,
  });
};

// 我的邮箱
const emailList: any = [];
let email_id_list: any = [];
const handleEmailInfo = async (rs: any) => {
  if (rs.emails.length > 0) {
    if (!email_id_list.includes(rs.emails[0].email_id)) {
      emailList.push(rs.emails[0]);
    }
    if (emailList.length > 0) {
      email_id_list = emailList.map((item: any) => item.email_id);
    }
    const sb = new Set(rs.email_readed);
    emailList.forEach((item: any) => {
      const timer = convertObjectToDateString(item.recv_time);
      item.time = new Date(timer).getTime();
    });

    emailList.sort((a: any, b: any) => b.time - a.time); // 排序
    const list = emailList.filter((item: any) => item.attachments[0].award_value == 0);
    const rewardList = emailList.filter(
      (item: any) => item.attachments[0].award_value > 0
    );
    const params = {
      email_readed: rs.email_readed,
      list,
      rewardList,
      email_id_list,
      hasNoRead: email_id_list.some((x: any) => !sb.has(x)),
    };
    await user.setEmailList(params);
  }
};

// 监听新收到邮箱
const handleNewEmail = (rs: any) => {
  //奖励邮箱
  if (rs.new_email.attachments[0].award_value > 0) {
    myEmail.value.rewardList.unshift(rs.new_email);
  } else {
    myEmail.value.list.unshift(rs.new_email);
    myEmail.value.email_id_list.push(rs.new_email.email_id)
  }
  myEmail.value.hasNoRead = true;
};

// 角色详情
const handleRoleInfo = async (data: any) => {
  setTimeout(async () => {
    await user.getRoleInfo(data);
  }, 1000)
};


// 角色VIP详情
const handleVipInfo = async (data: any) => {
  await user.getVIPInfo(data);
};
// 用户详情
const handleUserInfo = async (data: any) => {
  await user.getInfo(data);
  setTimeout(() => {
    getFirstStatus();
  }, 3000)
  // getRoleClubId();
};

// 监听金额变化
const handleUpdateMoney = async (data: any) => {
  if (data) {
    const newData = { ...roleInfo.value };
    newData.money = data.cur_money;
    await user.getRoleInfo(newData);
  }
};
// 余额变化
const handleUpdateRoleInfo = async (data: any) => {
  if (data?.id) {
    console.log("update-roleInfo---", data);
    // 因为这里返回的数据缺少了很多字段，所以需要这样处理
    const newData = {
      ...roleInfo.value,
      ...data,
    };
    await user.getRoleInfo(newData);
  }
};
// 获取充值信息
const getShopInfo = () => {
  const req = NetPacket.req_get_shop_info();
  PKwebsocket.instance.send(req, true)
};


// 获取已绑定的银行账号
const getMyBankList = () => {
  const req = NetPacket.req_bank_card_info_list();
  PKwebsocket.instance.send(req, true);
};

const dbClick = ref(false)
const currentTab = ref(0)
const tabbarClick = (item: any) => {
  const beforeActive = state.active

  // 双击判断
  // if (dbClick.value && item.name == 'home') {
  //   location.href = '/'
  // }
  setTimeout(() => {
    dbClick.value = false
  }, 1000)
  dbClick.value = true

  // 充提
  if ([3].includes(item.id)) {
    state.popoverShow = !state.popoverShow;
    if (state.popoverShow && isLocalLoggedIn.value) {
      getShopInfo();
      getMyBankList();
    }
  }

  if ([5].includes(item.id)) {
    state.popoverShow = false
    if (!isLocalLoggedIn.value) {
      isLogin.value = true;
      state.active = beforeActive;
      return;
    }
  }
  currentTab.value = item.id
  router.push(item.url);
};

if (location.href.includes("?relogin=1") && !Local.get("user")) { // 重新登录时打开弹窗
  setTimeout(() => {
    user.setLogin(true);
  }, 1000);
}
// 重复登录
eventBus.on('msg_notify_repeat_login', async () => {
  let login_time = 0
  try {
    login_time = sessionStorage.getItem('login_time') ? Number(sessionStorage.getItem('login_time')) : 0
  } catch { }
  if (new Date().getTime() - login_time > 120000) { // 登录后2分钟内忽略重复登录的消息
    Local.remove("user");
    system.setWsConnected(false)
    system.setLoggedIn(false)
    user.getUserLoginInfo(null);
    showDialog({
      title: t("home_page_offlineNotification"),
      content: t("home_page_offlineContent"),
      okText: t("home_page_offlineConfirm"),
      cancelText: t("home_page_modifyPassword"),
      onOk: async () => {
        location.href = "/?relogin=1";
      },
      onCancel: async () => {
        location.href = "/?relogin=1";
      },
    });
  }
});
// 充值成功，弹出提示
const handleDepositSuc = async (data: any) => {
  if (data?.amount) {
    showNotify.success(t("deposit_page_depSuccess")); // 充值成功需要弹出提示
  } else {
    showNotify.danger(t("deposit_page_depSuccess"));
  }
};
const resizeChange = () => {
  if (window.orientation === 90 || window.orientation === -90) {
    state.show = true;
  } else {
    state.show = false;
  }
};
// 获取所有收藏的游戏id集合
const resAllCollect = async (data: any) => {
  await User(pinia).getCollected(data.collected);
};
// 是否收藏游戏
const resCollect = async (data: any) => {
  if (data.rlt == 0) {
    let gameId = Local.get("gameId");
    if (allCollected.value.includes(gameId) || gameId === "COLLECT_CANCEL") {
      let arr = allCollected.value.filter((e: Number) => e != gameId);
      await user.getCollected(arr);
      showToast.success(t("collect_success_cancel"));
    } else {
      let arr = [...allCollected.value, gameId];
      await user.getCollected(arr);
      showToast.success(t("collect_success"));
    }
  } else if (data.rlt == 1) {
    showToast.warn(t("collect_success_limit"));
  } else {
    showToast.fail(t("Unknown_error"));
  }
};
// 游戏返回的链接
// 第三方游戏信息返回

const handleFirstStatusApi = (res: any) => {
  // status = 0 无首充
  // status = 1 参与首充x3
  // status = 3 参与��充100%
  sessionStorage.setItem("FirstRechargeStatus", res.status);
};

const gameUrlResult = async (message: any) => {
  await Page(pinia).setGameIsLoading(false);
  if (message.code != 0) {
    showToast.fail(message.msg);
    return;
  }
  if (message.url.indexOf("<!doctype html>") != -1) {
    message.url = `data:text/html;charset=utf-8,${encodeURIComponent(
      String(message.url)
    )}`;
  }
  // if ([23].includes(23)) {
  //   let newPage = window.open(message.url, '_blank');

  //   // newPage.document.write(data);//运行 HTML 代码
  //   newPage?.document.close();
  // } else {
  Local.set("gameUrl", message.url);
  state.popoverShow = false;
  router.push("/openGame");
  // }

  // 主动断开ws
  PKwebsocket.instance.pauseWs()
};

// 获取首冲状态
const getFirstStatus = () => {
  const reqFirst = NetPacket.req_first_recharge_status();
  PKwebsocket.instance.send(reqFirst, true, {
    callbackName: 'msg_notify_first_recharge_status',
    callback: handleFirstStatusApi
  });
};

//获取当前用户创建的俱乐部ID
// const getRoleClubId = () => {
//   // @ts-ignore
//   const reqFirst = NetPacket.req_get_create_club_id();
//   PKwebsocket.instance.send(reqFirst, true, {
//     callbackName: 'msg_notify_get_create_club_id',
//     callback: handleRoleClubId
//   });
// };

// const handleRoleClubId = (res: any) => {
//   console.log('俱乐部id', res)
//   Local.set('clubId', res.club_id[0] || 0)
// };

const handleShopInfoRes = async (rs: any) => {
  // 匹配出银行的支付方式
  const newArr = [...rs.rechargelist_by_paymenttype].filter((item: any) =>
    bankPayMethods.includes(item.paymenttype)
  );
  // 为了赋值 payname 字段
  newArr.forEach((item: any) => {
    bankPayType.forEach((item_1: any) => {
      if (item.paymenttype === item_1.paymenttype) {
        item._payname = item_1.payname;
      }
    });
  });
  console.log("newArr-----", newArr);
  const bankNewObj: any = newArr.find((item: any) => item.payname === "bankcard");
  const bankAll: any = [];
  if (bankNewObj.paymethod) {
    bankNewObj.paymethod.split(",").map((item: any, index: any) => {
      bankAll.push({
        ...bankNewObj,
        paymethod: item, // 没有用到
        _paymenttype: 100 + index, // 银行卡转账 100,  网银直连 101， 扫码支付 102
        _payname: `bankcard_${index}`,
      });
    });
  }
  // 非银行的支付方式
  const notBankArr = newArr
    .filter((item: any) => item.payname !== "bankcard")
    .map((item: any) => {
      return { ...item, _paymenttype: item.paymenttype * 100 };
    });
  const allBankList = [...bankAll, ...notBankArr].map((item: any) => {
    return {
      ...item,
      label: t(`api_${item._payname}`),
      value: item._paymenttype,
    };
  });
  // 需要过滤 limit 为 0 的数据, .filter((item: any) => item.limit)
  const discountList = rs.discount_list.map((dc: any) => {
    return {
      ...dc,
      text: dc.name,
      label: dc.name,
      value: dc.discount_ID,
    };
  });
  console.log("-------", discountList);
  const newObj: any = {
    ...rs,
    discount_list: discountList,
    rechargelist_by_paymenttype: allBankList,
  };
  await user.setShopInfoData(newObj);
};
const handleMyBankList = async (res: any) => {
  await user.setBankCardInfoData(res);
};


onBeforeMount(() => {
  // 异地登录提醒
  eventBus.on('msg_notify_diff_loc_login_notification', diffOfflineFunc)

  //获取第三方游戏返回url
  eventBus.on('msg_notify_3rd_game_login_result', gameUrlResult)

  // 请求收藏的游戏id集合
  eventBus.on('msg_notify_all_collected', resAllCollect)
  // 添加收藏
  eventBus.on('msg_notify_modify_collect', resCollect)
  eventBus.on('msg_notify_send_system_notice', onHander_system_notice)
  // 系统消息
  eventBus.on('msg_notify_sys_msg', onHandler_system_msg)
  // 用户信息
  eventBus.on('msg_notify_roleinfo_msg', handleRoleInfo)
  // 用户俱乐部ID
  // eventBus.on('msg_notify_get_create_club_id', handleRoleClubId)
  eventBus.on('msg_notify_user_info', handleUserInfo)
  // 回执监听
  eventBus.on('msg_notify_email_list', handleEmailInfo)
  eventBus.on('msg_notify_vip_info', handleVipInfo)
  eventBus.on('msg_notify_money_update2', handleUpdateMoney)
  // 用户金额变化后，重新拉取金额
  eventBus.on('msg_notify_roleinfo_with_id', handleUpdateRoleInfo)
  // 充值成功
  eventBus.on('msg_notify_recharge_success_from_third', handleDepositSuc)
  // 监听新邮件
  eventBus.on('msg_notify_new_email', handleNewEmail)
  // 获取充值方式列表
  eventBus.on('msg_notify_req_get_shop_info', handleShopInfoRes)
  // 提现
  eventBus.on('msg_notify_bank_card_info_list', handleMyBankList)
});

onMounted(async () => {
  init(String(route.name));
  Local.set("agentid", route.query.uid || "0");

  // 没十秒请求一下消息？
  // setInterval(() => {
  //   isLocalLoggedIn && Page(pinia).getUnread()
  // }, 10000);
});

onBeforeUnmount(() => {
})

watch(
  () => shopInfoData.value,
  (n: any) => {
    state.isMainDeposit = n.rechargelist_by_paymenttype.every(
      (item: any) => !item.status
    ); // 是否全部充值方式都维护
    if (state.isMainDeposit) {
      state.walletList.forEach((item: any) => {
        if (item?.key === "deposit") {
          item.img = "/imgs/tabbar/cz_close.webp";
        }
      });
    }
  }
);
watch(
  () => bankCardInfoList.value,
  (n: any) => {
    state.isMainWidthdraw = !n.bank_card_maintain_status && !n.usdt_maintain_status; // 是否全部提现方式都维护
    if (state.isMainWidthdraw) {
      state.walletList.forEach((item: any) => {
        if (item?.key === "withdrawals") {
          item.img = "/imgs/tabbar/tx_close.webp";
        }
      });
    }
  }
);

watch(
  () => route.name,
  (n: any) => {
    init(String(n));
    state.popoverShow && (state.popoverShow = false)
    if (n != "openGame") {
      let event = "onorientationchange" in window ? "orientationchange" : "resize";
      window.addEventListener(event, resizeChange, false);
    }
  }
);

// 刷新时禁止点击
watch(() => pageLoading.value, (v) => {
  const bodyEl = document.querySelector('body')
  if (!bodyEl) return
  if (v) {
    bodyEl.style.pointerEvents = 'none';
  } else {
    bodyEl.style.pointerEvents = 'auto';
  }
}, {
  immediate: true
})

if (window.matchMedia("(display-mode: standalone)").matches) {
  document.body.style.height = '100vh'
  document.body.style.setProperty('--nut-notify-pt', `env(safe-area-inset-top)`);
}



</script>
<style lang="scss">
.page-loading-container {
  width: 100%;
  // height: calc(100 * var(--vh) - 60px);
  padding-top: 45vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.router-page {
  // opacity: 0;
  // &.fadeIn {
  //   animation: fadeInPage 0.05s linear forwards;
  // }   
}

@keyframes fadeInPage {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

.home_sider_menu {
  width: 100%;
  height: 100%;
  background-image: url('/imgs/home/public_bg.webp');
  background-size: 80%;
  // height: calc(100 * var(--vh) - 1px);

  .home_header {
    margin: 12px 0 8px 0;
  }

  .home_sier_main {
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: 100%;
  }

  .category-details {
    .query {
      margin: 0 0 10px 0 !important;
    }
  }
}
</style>
<style lang="scss" scoped>
.app {
  user-select: none !important;
  position: relative;
  display: flex;
  flex-direction: column;
  min-height: calc(var(--vh, 1vh) * 100);

  &.has_header {
    padding-top: calc(44px + env(safe-area-inset-top));
  }

  .app_header {
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 10;
    padding-top: calc(env(safe-area-inset-top));
    background-image: url('/imgs/home/public_bg.webp');
    background-size: 80%;
  }

  .amount_box {
    display: flex;
    align-items: center;
    background-color: #1D1C48;
    height: 28px;
    padding: 0 8px 0 6px;
    border-radius: 14px;

    >span {
      margin: 0 6px;
    }

    .plus {
      width: 16px;
      height: 16px;
    }
  }

  .placeholder {
    height: 44px;
  }

  :deep(.nut-tabbar) {
    background-color: #100e26;
    border: none;

    &::before {
      content: "";
      width: 100%;
      height: 30px;

      // background-color: red;
      position: absolute;
      top: -18px;
      left: 50%;
      transform: translateX(-50%);
      background-image: url(/imgs/home/tabbar_bg.png);
      background-size: cover;
      background-position: center;
      z-index: -1;
    }
  }

  .tt {
    display: inline-block;
    z-index: 1;
    width: 40px;
    height: 40px;
    position: absolute;
    top: -40px;
    left: 50%;
    transform: translateX(-50%);
  }
}

.login_pop {
  display: flex;
  width: 355px;
  height: 100%;
  margin: 0 auto;
  align-items: center;
  justify-content: center;
}

.diff_offline_dialog {
  padding: 20px 20px 32px 20px;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  line-height: 21px;

  .btn {
    width: 100%;
    margin-top: 24px;
    height: 44px;
    background: linear-gradient(180deg, #5567ff 0%, #9e1eff 100%);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 14px;
    font-weight: 500;
    line-height: 14px;
  }
}

.nut-tabbar-item__icon--unactive {
  color: #fff !important;
}

.nut-tabbar-item {
  color: #5d69ff;
  margin-bottom: 7px;
  align-items: end;
  /* background-color: #301a73; */
}

.item {
  height: 35px;
}

// :deep(.nut-popover .nut-popover-content) {
//   //opacity: none;
// }

.tab_style {
  width: 32px;
}

.popover_bg {
  position: fixed;
  bottom: 0;
  width: 100%;
  // background-size: 100% 100%;
  z-index: 99;
  display: flex;
  height: 0;
  flex-direction: column;

  .popover_bg_close {
    flex: 1;
  }

  &_main {
    background: linear-gradient(180deg, #131232 6.18%, #100e26 100%);
    border-radius: 6px;
    display: flex;
    justify-content: space-around;
    border-top: 1px solid transparent;
    border-image: linear-gradient(to right, transparent, white, transparent) 1;
    transition: all 0.3s;
    height: 0;

    >div {
      display: flex;
      flex: 1;
      flex-direction: column;
      margin-top: 12px;
      color: #8e82c2;
      align-items: center;

      >img {
        width: 38px;
        height: 38px;
      }
    }
  }
}

.pop_height {
  height: calc(var(--vh, 1vh) * 100);
}

.pop_height_main {
  height: calc(165px);
}
</style>
